/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.axiom.persistence;

import com.axiom.utility.IdGenerator;
import com.axiom.vo.course_detail;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author Shuhail
 */
public class course_detail_persist {
    
    Session sess = null;
    Transaction tx = null;
    
    public static course_detail_persist getInstance() {
        
        return new course_detail_persist();
    }
    
    public course_detail_persist() {
        
        SessionFactory sf = new Configuration().configure().buildSessionFactory();
        sess = sf.openSession();
        tx = sess.beginTransaction();
    }
    
    
    public boolean insertFresh(course_detail detail) {
        System.out.println("Inside Course Persist");
        try {
            detail.setCourse_id(IdGenerator.getInstance().getValue(this.getTheLastPK()));
        sess.save(detail);
        tx.commit(); 
        }catch(Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    
    
    public List getAllDetails() {
        
        List result = null;
        try {
            Query query = sess.getNamedQuery("getTheLastPKForCourseDetail");
            result = query.list();
        }
        catch(Exception e) {
            
        }
       
        return result;
    }
    public String getTheLastPK() {
        
        List list = this.getAllDetails();
        Iterator it = list.iterator();
        List<String> pkList = new ArrayList<String>();
        while(it.hasNext()) {
            course_detail detail =(course_detail)it.next();
            pkList.add(detail.getCourse_id());
        }
          String id = IdGenerator.getInstance().getTheLastPK(pkList);
          
          return id;
    }
    
    
    public int deleteCourse(String course_id) {
        
        Query query = sess.getNamedQuery("deleteCourse");
        query.setString("course_id", course_id);
        try {
            
            int del = query.executeUpdate();
            tx.commit();
            return del;
        }
        catch(Exception e) {
            
            return 0;
        }
    }
    
    public static void main(String[] args) {
        
        String s=new course_detail_persist().getTheLastPK();
        System.out.print(new course_detail_persist().deleteCourse("C14"));
    }
    
}
